/*
 * Copyright 2013 JROSE
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.jrose.service.loader.support.creator;

import org.jrose.core.util.RandomUtils;
import org.jrose.entity.config.Lineup;
import org.jrose.entity.data.Team;
import org.jrose.entity.data.TeamLineup;
import org.jrose.entity.data.User;
import org.jrose.service.loader.support.LoaderProvider;

import java.util.LinkedList;
import java.util.List;

public class TeamCreator extends AbstractCreator<Team> {
    private final Team team;

    public TeamCreator(LoaderProvider loaderProvider, User user) {
        super(loaderProvider);
        team = Team.newInstance(user.getId());
        team.setName("TEAM OF " + user.getUsername());
        team.setDescription("");
    }

    @Override
    public Team fin() {
        loaderProvider.getTeamPersistence().persist(team);

        List<Lineup> lineups = loaderProvider.getLineupLoader().loadInitialAvailableLineups();
        List<TeamLineup> teamLineups = new LinkedList<>();
        for (Lineup lineup : lineups) {
            TeamLineup teamLineup = TeamLineup.newInstance(team.getId(), lineup.getId());
            teamLineups.add(teamLineup);

        }
        RandomUtils.randomListElement(teamLineups).setActive(true);
        for (TeamLineup teamLineup : teamLineups) {
            loaderProvider.getTeamLineupPersistence().persist(teamLineup);
        }

        return team;
    }
}
